package com.lf.web.service;

import com.lf.data.Form;
import com.lf.data.Global;
import com.lf.data.Page;
import com.lf.web.service.system.user.User;
import com.opensymphony.xwork2.ActionContext;
import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public abstract class ServiceSupport {

    public static final String SUCCESS = "success";
    public static final String NONE = "none";
    public static final String LIST = "list";
    public static final String ADD = "add";
    public static final String SAVE = "save";
    public static final String UPDATE = "update";
    public static final String DELETE = "delete";

    protected ActionContext context;
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected PrintWriter writer = null;
    protected Form form;

    private static final Logger LOGGER = Logger.getLogger(ServiceSupport.class);

    public ServiceSupport() {
        context = ActionContext.getContext();
        request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST);
        response = (HttpServletResponse) context.get(StrutsStatics.HTTP_RESPONSE);
        form = new Form(request);
    }

    public User getUser() {
        return (User) context.getSession().get(Global.SESSION_USER);
    }

    public Page getPage() {
        Page page = new Page();
        form.getBean(page, false, "page");
        return page;
    }

    public KeyUpdate getKeyUpdate(Class clazz) {
        KeyUpdate keyUpdate = new KeyUpdate(clazz);
        form.getBean(keyUpdate, false, "update");
        return keyUpdate;
    }

    public abstract String execute();

    public String error(int code) {
        try {
            response.sendError(code);
        } catch (IOException e) {
            LOGGER.error("设置http状态错误(" + code + "):" + e);
        }
        return NONE;
    }

    public boolean out(Object content) {
        if (writer == null) {
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                LOGGER.error("获取页面输出句柄异常：" + e);
                return false;
            }
        }
        writer.write(String.valueOf(content));
        return true;
    }
}
